package com.sharp.core.graphics.gl;

import static org.lwjgl.opengl.GL11.*;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;

import com.sharp.core.graphics.Color;
import com.sharp.core.graphics.Graphic;
import com.sharp.core.graphics.UnColor;
import com.sharp.core.raytrace.Camera;

public class OpenGLGraphic extends Graphic {

	//private ByteBuffer backBuffer;;
	private int[] backBuffer;
	private int backBufferCounter;
	
	private int width;
	private int height;
	
	@Override
	public void init(int width, int height, int bpp) {
		this.width = width;
		this.height = height;
		
		Display.setTitle("TestScene");
		try {
			Display.setDisplayMode(new DisplayMode(width, height));
			Display.setFullscreen(false);
			Display.setVSyncEnabled(false);
			Display.create();
		} catch (LWJGLException ex) {}


		glDisable(GL_LIGHTING);
		glDisable(GL_BLEND);
		glDisable(GL_DEPTH_TEST);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(0, width, height, 0, -1, 1);
		
		backBuffer = new int[width*height];
		//backBuffer = ByteBuffer.allocateDirect(width*height*3).order(ByteOrder.nativeOrder());
		backBufferCounter = 0;;
		
		setGraphic(this);
	}

	@Override
	public void drawPixel(Camera cam, int x, int y, Color c) {
		x += cam.getStartX();
		y += cam.getStartY();
		glColor3f(c.getR(), c.getG(), c.getB());
		glBegin(GL_POINTS);
			glVertex2i(x, y);
		glEnd();
	}

	@Override
	public void clean() {
		glClear(GL_COLOR_BUFFER_BIT);
	}

	@Override
	public void update() {
		Display.update();
	}
	
	public synchronized void drawToBackBuffer(Camera cam, int x, int y, UnColor c) {
		x += cam.getStartX();
		y += cam.getStartY();
		backBuffer[y*width+x] = c.intValue();
		//backBuffer.put((byte) (c.getR()*255));
		//backBuffer.put((byte) (c.getG()*255));
		//backBuffer.put((byte) (c.getB()*255));
	}
	
	public void drawToBackBufferLinearly(Color c) {
		//backBuffer[backBufferCounter] = c.intValue();
	}

	public void drawBackBuffer() {
		backBufferCounter = 0;
		/*backBuffer.flip();
		glDrawPixels(width, height, GL_RGB, GL_UNSIGNED_BYTE, backBuffer);*/
		Color c = new Color();
		glBegin(GL_POINTS);
		for ( int x = 0; x < width; ++x ) {
			for ( int y = 0; y < height; ++y ) {
				c.setTo(backBuffer[y*width+x]);
				glColor3f(c.getR(), c.getG(), c.getB());
				glVertex2i(x, y);
			}
		}
		glEnd();
	}
	
}
